package com.am.mosl.cityandroid.leftmenu;

import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.am.mosl.cityandroid.R;
import com.am.mosl.cityandroid.activity.BaseActivity;
import com.am.mosl.cityandroid.bean.AccountBean;
import com.am.mosl.cityandroid.bean.MData;
import com.am.mosl.cityandroid.constant.HttpConstant;
import com.am.mosl.cityandroid.message.LoginMessage;
import com.am.mosl.cityandroid.util.SettingUtils;

import de.greenrobot.event.EventBus;

/**
 * Created by mosl on 14-6-28.
 * 
 */
public class MessageCentetActivity extends BaseActivity implements
		OnScrollListener {

	private ListView listView;
	private int page;
	private List<MData> data = new ArrayList<MData>(); // 获取的 LIST 是个容器
	private List<MData> data2 = new ArrayList<MData>(); // 传进 ADAPTER 的 LIST
	private MessageListAdapter adapter;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				adapter = new MessageListAdapter(MessageCentetActivity.this,
						data2);
				listView.setAdapter(adapter);

				break;
			case 2:

				break;
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.message_center);
		initActionBar();

		page = 1;

		listView = (ListView) findViewById(R.id.message_list); // 获取id是list的ListView

		initAdapter(page);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				MData datah = adapter.getData(arg2);

				String title = datah.getMessage_title();
				String time = datah.getCreatedate();
				String des = datah.getMessage_description();
				String content_id = datah.getContent_id();

				String mes_id = datah.getMessage_id();
				HaveRead(mes_id);

				Intent i = new Intent(MessageCentetActivity.this,
						MessageDetailActivity.class);

				i.putExtra("title", title);
				i.putExtra("time", time);
				i.putExtra("des", des);
				i.putExtra("content_id", content_id);

				startActivity(i);

			}

		});

	}

	protected void HaveRead(String mes_id) {
		// TODO Auto-generated method stub
		if (isNetworkAvailable(MessageCentetActivity.this)) {
			FinalHttp finalHttp = new FinalHttp();
			AjaxParams params = new AjaxParams();

			AccountBean accountBean = new AccountBean();
			accountBean = SettingUtils.getUserInfo(MessageCentetActivity.this);
			String token = accountBean.getToken();

			params.put("messageid", mes_id);
			params.put("token", token);

			finalHttp.post(HttpConstant.ReadMessage, params,
					new AjaxCallBack<Object>() {
						@Override
						public boolean isProgress() {
							return super.isProgress();
						}

						@Override
						public void onSuccess(Object o) {
							super.onSuccess(o);
							try {
								JSONObject jsonObject = new JSONObject(o
										.toString());

								String status = (String) jsonObject
										.opt("status");
								String msg = (String) jsonObject.opt("msg");

								if (status.equals("2")) {

									SettingUtils
											.RemoveAccount(MessageCentetActivity.this);
									LoginMessage message = new LoginMessage();
									message.setType(LoginMessage.QUIT);
									EventBus.getDefault().post(message);

									Toast.makeText(MessageCentetActivity.this,
											"帐号验证失败，请重新登录", Toast.LENGTH_SHORT)
											.show();
									MessageCentetActivity.this.finish();
								}

							} catch (JSONException e) {
								e.printStackTrace();
							}
						}

					});

		} else {
			Toast.makeText(MessageCentetActivity.this, "网络未连接",
					Toast.LENGTH_SHORT).show();
		}

	}

	private void initAdapter(final int offset) {
		// TODO Auto-generated method stub

		AccountBean accountBean = new AccountBean();
		accountBean = SettingUtils.getUserInfo(MessageCentetActivity.this);
		String token = accountBean.getToken();

		String offsett = Integer.toString(offset);

		// TODO Auto-generated method stub
		if (isNetworkAvailable(MessageCentetActivity.this)) {
			FinalHttp finalHttp = new FinalHttp();
			AjaxParams params = new AjaxParams();

			params.put("token", token);
			params.put("offset", offsett);

			finalHttp.post(HttpConstant.GetMessage, params,
					new AjaxCallBack<Object>() {
						@Override
						public boolean isProgress() {
							return super.isProgress();
						}

						@Override
						public void onSuccess(Object o) {
							super.onSuccess(o);
							try {
								JSONObject jsonObject = new JSONObject(o
										.toString());

								JSONArray jsonArray = (JSONArray) jsonObject
										.opt("data");
								String status = (String) jsonObject
										.opt("status");
								String msg = (String) jsonObject.opt("msg");
								if (status.equals("1")) {
									if (offset == 1) {
										data = JSON.parseArray(
												jsonArray.toString(),
												MData.class);
										data2 = data;
										mHandler.sendEmptyMessage(1);
										if (data.size() == 10) {
											appendlist(data);
										}
									} else {
										data.clear();
										data = JSON.parseArray(
												jsonArray.toString(),
												MData.class);
										appendlist(data);
									}
								} else if (status.equals("2")) {

									SettingUtils
											.RemoveAccount(MessageCentetActivity.this);
									LoginMessage message = new LoginMessage();
									message.setType(LoginMessage.QUIT);
									EventBus.getDefault().post(message);

									Toast.makeText(MessageCentetActivity.this,
											"帐号验证失败，请重新登录", Toast.LENGTH_SHORT)
											.show();
									MessageCentetActivity.this.finish();
								} else {
									if (offset == 1) {
										Toast.makeText(
												MessageCentetActivity.this,
												"获取信息失败：" + msg,
												Toast.LENGTH_SHORT).show();
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					});

		} else {
			Toast.makeText(MessageCentetActivity.this, "网络未连接",
					Toast.LENGTH_SHORT).show();
		}
	}

	protected void appendlist(List<MData> data3) {
		// TODO Auto-generated method stub

		if (page == 1) {

			page = page + 1;
			initAdapter(page);

		} else {

			int nicount = data3.size();// 测试判断剩下的数量
			if (nicount == 10) {

				adapter.append(data3);
				page = page + 1;
				initAdapter(page);

			} else if (nicount < 10 && nicount > 0) {

				adapter.append(data3);

			} else {

			}
		}

	}

	private void initActionBar() {

		View Back = (View) findViewById(R.id.layout_action_bar_back);
		Back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				onBack();
			}
		});
		TextView title = (TextView) findViewById(R.id.tittle);
		title.setText("消息中心");
		View view = (View) findViewById(R.id.right_tittle);
		view.setVisibility(View.GONE);

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	/**
	 * 判断网络是否可用
	 * 
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager mgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] info = mgr.getAllNetworkInfo();
		if (info != null) {
			for (int i = 0; i < info.length; i++) {
				if (info[i].getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}

}